package com.seventh.tickets.service.Impl;

import com.seventh.tickets.base.Result;
import com.seventh.tickets.base.TransResult;
import com.seventh.tickets.entity.Booking;
import com.seventh.tickets.entity.Concert;
import com.seventh.tickets.entity.ConcertTicket;
import com.seventh.tickets.enums.BookingErrorCode;
import com.seventh.tickets.enums.ConcertErrorCode;
import com.seventh.tickets.enums.TicketErrorCode;
import com.seventh.tickets.repository.BookingRepository;
import com.seventh.tickets.repository.ConcertRepository;
import com.seventh.tickets.repository.ConcertTicketRepository;
import com.seventh.tickets.service.BookingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BookingServiceImpl implements BookingService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final BookingRepository bookingRepository;
    private final ConcertRepository concertRepository;
    private final ConcertTicketRepository concertTicketRepository;

    public BookingServiceImpl(BookingRepository bookingRepository, ConcertRepository concertRepository, ConcertTicketRepository concertTicketRepository) {
        this.bookingRepository = bookingRepository;
        this.concertRepository = concertRepository;
        this.concertTicketRepository = concertTicketRepository;
    }

    @Override
    public Result insertBooking(Long concertId, Long userId, String userIdCard, String seatType) throws Exception {
        Result result = new TransResult();
        // fixme 待重构

        Concert concert = concertRepository.getOne(concertId);
        if (concert == null) {
            logger.info(String.format("错误，未查到该演唱会信息，演唱会id为%s", concertId));
            result.setErrorCode(ConcertErrorCode.CONCERT_IS_NOT_EXISTS);
            throw new Exception("错误，未查到该演唱会信息，演唱会id为" + concertId);
        }
        ConcertTicket concertTicket = concertTicketRepository.findByConcertIdAndSeatGrade(concertId, seatType);
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//                String date = df.format(new Date());
        Booking booking = new Booking();
        booking.setConcert(concert);
        booking.setTicket(concertTicket);
        booking.setUserId(userId);
        booking.setUserIdCard(userIdCard);
        booking.setSeatType(seatType);
        booking.setBookingPrice(concertTicket.getSeatPrice());
        booking.setBookingTime(new Date());
        booking = bookingRepository.save(booking);
        if (booking.getBookingId() > 0) {
//                    ConcertTicket concertTicket = concertTicketRepository.findByConcertIdAndSeatGrade(concertId, seatType);
            if (concertTicket == null) {
                logger.info(String.format("未查询到该演唱会%d，座位类别为%s的信息", concertId, seatType));
                result.setErrorCode(TicketErrorCode.TICKET_IS_NOT_EXISTS);
                throw new Exception("未查询到该演唱会" + concertId + "，座位类别为" + seatType + "的信息");
            } else {
                int seatLeft = concertTicket.getSeatLeft();
                if (seatLeft > 0) {
                    concertTicket.setSeatLeft(concertTicket.getSeatLeft() - 1);
                    concertTicket = concertTicketRepository.save(concertTicket);
                    if (concertTicket.getConcert().getConcertId() > 0) {
                        result.setData(booking.getBookingId());
                        return result;
                    } else {
                        logger.info("用户购票，座位剩余数量-1失败!");
                        result.setErrorCode(TicketErrorCode.TICKET_ADD_EXCEPTION);
                        throw new Exception("用户购票，座位剩余数量-1失败!");
                    }
                } else {
                    bookingRepository.delete(booking.getBookingId());
//                            Booking booking1 = new Booking();
//                            booking1.setBookingTime("该场次已经售完");
//                            return booking1;
                    logger.info("该场次已经售完!");
                    result.setErrorCode(TicketErrorCode.TICKET_IS_SOLD_OUT);
                    throw new Exception("该场次已经售完!");
                }
            }
        } else {
            logger.info(String.format("保存购买票失败，演唱会id为%d", concertId));
            result.setErrorCode(ConcertErrorCode.CONCERT_ADD_EXCEPTION);
            throw new Exception("保存购买票失败，演唱会id为" + concertId);
        }
    }

    @Override
    public List<Booking> findByUserIdCard(String userIdCard) {
        return bookingRepository.findAllByIdCard(userIdCard);
    }

    @Override
    public List<Booking> findByUserId(Long userId) {
        return bookingRepository.findAllByUserId(userId);
    }

    /**
     * 退票
     *
     * @param bookingId
     * @param concertId
     * @param userId
     * @return
     */
    @Override
    public Result refundBooking(Long bookingId, Long concertId, Long userId) {
        Result result = new TransResult();

        // 订票数据是否存在
        if (!bookingRepository.exists(bookingId)) {
            result.setErrorCode(BookingErrorCode.BOOKING_IS_NOT_EXISTS);
            return result;
        }

        Booking booking = bookingRepository.getOne(bookingId);
        Concert concert = booking.getConcert();

        // 演出是否已开始
        if (concert.getConcertStartTime().before(new Date())) {
            result.setErrorCode(ConcertErrorCode.CONCERT_IS_STARTED);
            return result;
        }

        ConcertTicket ticket;
        ticket = booking.getTicket();
        // 退票后席位+1
        ticket.setSeatLeft(ticket.getSeatLeft() + 1);

        // 保存席位数据
        concertTicketRepository.save(ticket);
        // 删除订票数据
        bookingRepository.delete(bookingId);

        return result;
    }
}